package com.pan.admin.module.common.controller;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.tree.TreeUtils;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.pan.admin.cache.DistrictCache;
import com.pan.admin.module.common.entity.DistrictPO;
import com.pan.admin.module.common.entity.vo.RespAppDistrictVO;
import com.pan.admin.module.common.service.DistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 地区编码相关
 */
@RestController
@RequestMapping("/common/district")
public class DistrictController {

    @Autowired
    private DistrictService districtService;

    /**
     *  返回地区编码树
     *
     *  @return ResultVO
     */
    @GetMapping("/getTree")
    public ResultVO<Object> getTree() {
        List<Map<String, Object>> respDistrictVO = DistrictCache.DISTRICT_TREE_MAP.get("tree", () -> {
            List<DistrictPO> list = districtService.list();
            //  只保留县级市
            CollUtils.filter(list, t -> Eq.str(t.getType(), "3") && !t.getName().endsWith("市"));
            //  改变原有县级市的父类值，前端好展示
            IteratorUtils.array(list, t -> {
                if (Eq.str(t.getType(), "3")) {
                    t.setPCode(t.getCode().substring(0, 2) + "0000");
                }
            });
            List<RespAppDistrictVO> respAppDistrictVOS = CopyUtils.copyList(list, RespAppDistrictVO.class);
            return TreeUtils.create(respAppDistrictVOS, 3, true);
        });
        return ResultVO.suc(respDistrictVO);
    }

}
